<template>
  <a-drawer
    title="添加成员"
    :maskClosable="true"
    :visible="visible"
    :destroyOnClose="true"
    :width="600"
    :body-style="{ paddingBottom: '80px' }"
    @close="closeModal"
  >
    <a-alert
      showIcon
      message="未注册手机号添加后状态为“待激活”，业务类操作无法选择该成员。请及时通知该成员登录手机号自动激活。"
      type="info"
      class="mb-10"
    />
    <a-tabs v-model:activeKey="activeKey" class="mb-10" :tabBarStyle="{borderBottom:'1px solid #f0f0f0'}">
      <a-tab-pane v-for="item of infoTabs" :key="item.key" :tab="item.title" />
    </a-tabs>
    <a-form layout="vertical" key="edit_content">
      <template v-if="activeKey == 'basic'">
        <a-form-item label="成员头像" v-bind="validateInfos.avatar">
          <a-upload
            :action="imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            :multiple="false"
            v-model:file-list="fileList"
            @change="handleUploadChange"
            name="image"
            :data="{ dir: 'org_personal' }"
            accept="image/jpg,image/jpeg,image/gif,image/png"
            list-type="picture-card"
          >
            <div v-if="fileList.length < 1">
              <PlusOutlined />
              <div style="padding-top: 4px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="成员姓名" v-bind="validateInfos.realname">
          <a-input
            placeholder="请输入成员姓名"
            :maxlength="10"
            v-model:value="modelRef.realname"
          />
        </a-form-item>
        <a-form-item label="成员手机号" v-bind="validateInfos.phone">
          <a-input
            :disabled="id ? true : false"
            :addon-before="modelRef.phone_country"
            placeholder="请输入成员手机号码"
            v-model:value="modelRef.phone"
          />
        </a-form-item>
        <a-form-item label="邮箱地址">
          <a-input
            placeholder="请输入邮箱地址"
            v-model:value="modelRef.email"
          />
        </a-form-item>
        <a-form-item label="工作电话">
          <a-input
            placeholder="请输入工作电话"
            v-model:value="modelRef.work_phone"
          />
        </a-form-item>

        <a-form-item label="工号" v-bind="validateInfos.job_number">
          <a-input
            placeholder="请输入员工工号"
            v-model:value="modelRef.job_number"
          />
        </a-form-item>
      </template>
      <template v-if="activeKey == 'work'">
        <a-form-item label="入职时间" v-bind="validateInfos.induction_time">
          <a-date-picker
            v-model:value="modelRef.induction_time"
            type="date"
            placeholder="请选择入职时间"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="所属角色" v-if="!isAdmin">
          <a-select
            placeholder="请选择角色"
            :options="roleList"
            v-model:value="modelRef.role_id"
          />
        </a-form-item>
        <a-form-item label="所属部门" v-bind="validateInfos.department">
          <TreeSelect
            v-model:value="modelRef.department"
            :tree-data="departmentTreeData"
            allow-clear
            multiple
            placeholder="请选择成员所属部门"
          ></TreeSelect>
        </a-form-item>
        <a-form-item label="职位" v-bind="validateInfos.position">
          <a-input
            placeholder="请输入成员职位"
            v-model:value="modelRef.position"
          />
        </a-form-item>
        <a-form-item label="职称" v-bind="validateInfos.work_name">
          <a-input
            placeholder="请输入职称"
            v-model:value="modelRef.work_name"
          />
        </a-form-item>
        <a-form-item label="直属上级">
          <a-tag
            v-if="selectedMember"
            :closable="true"
            @close="handleTagClose"
            color="processing"
          >
            {{ selectedMember.realname }}
          </a-tag>
          <a-button type="primary" shape="circle" @click="chooseMember">
            <template #icon><EditOutlined /></template>
          </a-button>
        </a-form-item>
      </template>
      <template v-if="activeKey == 'person'">
        <a-form-item label="成员性别" v-bind="validateInfos.gender">
          <a-radio-group
            :options="genderOptions"
            v-model:value="modelRef.gender"
          />
        </a-form-item>
        <a-form-item label="出生年月" v-bind="validateInfos.birthday">
          <a-date-picker
            v-model:value="modelRef.birthday"
            type="date"
            placeholder="请选择出生年月"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="政治面貌">
          <a-select
            placeholder="请选择政治面貌"
            :options="politicalOptions"
            v-model:value="modelRef.political_type"
          />
        </a-form-item>
        <a-form-item label="成员人脸照片">
          <a-upload
            :action="imgAction"
            :headers="{ 'org-token': $store.getters.token }"
            :multiple="false"
            v-model:file-list="filefaceImage"
            @change="handleUploadFaceChange"
            name="image"
            :data="{ dir: 'org_personal' }"
            accept="image/jpg,image/jpeg,image/gif,image/png"
            list-type="picture-card"
          >
            <div v-if="filefaceImage.length < 1">
              <PlusOutlined />
              <div style="padding-top: 4px">上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </template>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
    </div>
    <ChooseOrgMember
      :visible="chooseMemberVisible"
      :getDetail="true"
      :deptDisabled="true"
      :uMax="1"
      @request="$utils.commonRequest"
      @close="closeChooseMemberModal"
      @success="handleMemberSelect"
    />
  </a-drawer>
</template>

<script>
import { computed, defineComponent, reactive, ref, toRaw, watch } from "vue";
import { Form, message, TreeSelect } from "ant-design-vue";
import moment, { Moment } from "moment";
import _ from "lodash";
import request from "../../../../common/utils/request";
import utils from "../../../../common/utils/utils";
import { ChooseOrgMember } from "bl-common-vue3";
import { EditOutlined, PlusOutlined } from "@ant-design/icons-vue";
import store from "../../../../store";

const useForm = Form.useForm;

export default defineComponent({
  name: "AddMember",
  components: { TreeSelect, EditOutlined, ChooseOrgMember, PlusOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [Number, String],
      default: 0,
    },
  },
  setup(props, context) {
    const { post, put } = request;
    const isAdmin = computed(
      () => store.getters.userInfo.admin_uid == modelRef.uid
    );
    const departmentTreeData = ref([]);

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      context.emit("closeAdd");
    };

    /**
     * @description: 表单字段
     */
    const modelRef = reactive({
      // todo.. 企业邮箱待调整
      uid: 0,
      realname: "",
      department: [],
      phone_country: "86",
      phone: "",
      work_phone: "",
      email: "",
      position: "",
      gender: "1",
      role_id: undefined,
      job_number: "",
      induction_time: undefined,
      avatar: "",
      work_name: "", // 职称
      political_type: undefined, // 政治面貌
      birthday: undefined, // 出生日期
      face_image: "",
    });

    /**
     * @description: 验证规则
     */
    const rulesRef = reactive({
      realname: [{ required: true, message: "成员姓名为必填项" }],
      phone: [{ required: true, message: "成员手机号码为必填项" }],
      department: [{ required: true, message: "所属部门为必选项" }],
    });

    const chooseMemberVisible = ref(false);
    const chooseMember = () => {
      chooseMemberVisible.value = true;
    };

    // 关闭选择成员弹窗
    const closeChooseMemberModal = () => {
      chooseMemberVisible.value = false;
    };

    // 成员选中
    const selectedMember = ref();
    const handleMemberSelect = (data) => {
      selectedMember.value = data.user[0];
      closeChooseMemberModal();
    };

    const handleTagClose = () => {
      selectedMember.value = null;
    };

    /**
     * @description: 手机号正则验证
     */
    const phoneFormat = (val, preVal) => {
      if (val && val.length > 11) {
        modelRef.phone = preVal;
        return;
      }
      if (val.length == 11 && !utils.phoneReg.test(val)) {
        message.error("请输入正确的手机号码！");
        return;
      }
      const reg = /^[0-9]*$/;
      if (reg.test(val)) {
        modelRef.phone = val;
      } else {
        modelRef.phone = preVal;
      }
    };
    watch(
      () => modelRef.phone,
      (phone, prePhone) => {
        phoneFormat(phone, prePhone);
      }
    );

    watch(
      () => store.getters.departmentList,
      (val) => {
        let _val = _.cloneDeep(val);
        if (!_val[0]?.is_direct_member) {
          _val[0].selectable = false;
        } else {
          _val[0].selectable = true;
        }
        departmentTreeData.value = _.cloneDeep(_val);
      }
    );

    /**
     * @description: 创建表单
     */
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    /**
     * @description: 提交表单
     */
    const onSubmit = () => {
      validate()
        .then(() => {
          let params = { ...toRaw(modelRef), needMsg: true };
          if (params.induction_time) {
            params.induction_time = params.induction_time.format("YYYY-MM-DD");
          }
          if (params.birthday) {
            params.birthday = params.birthday.format("YYYY-MM-DD");
          }
          params.department = params.department.length
            ? params.department.join(",")
            : undefined;
          if (selectedMember.value) {
            params.higher_uid = selectedMember.value.uid;
          }
          const success = (res) => {
            message.success(res.msg || "保存成功");
            context.emit("success", "member");
          };
          post("/org", "/department/user", params).then((res) => success(res));
        })
        .catch((err) => {
          console.log("error", err);
        });
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      getRoleList();
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          selectedMember.value = null;
          fileList.value = [];
          activeKey.value = "basic";
        }
      }
    );

    const roleList = ref([]);
    const getRoleList = () => {
      request.get("/org", "/department/role").then((res) => {
        roleList.value = res.list.map((item) => ({
          value: item.id,
          label: item.name,
        }));
      });
    };

    // 成员头像
    const fileList = ref([]);
    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.avatar = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.avatar = "";
      }
      fileList.value = resFileList;
    };

    const activeKey = ref("basic");
    const filefaceImage = ref([]);
    const infoTabs = ref([
      {
        title: "基本信息",
        key: "basic",
      },
      {
        title: "工作信息",
        key: "work",
      },
      {
        title: "个人信息",
        key: "person",
      },
    ]);

    const handleUploadFaceChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              modelRef.face_image = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        modelRef.face_image = "";
      }
      filefaceImage.value = resFileList;
    };

    return {
      isAdmin,
      closeModal,
      validateInfos,
      resetFields,
      modelRef,
      onSubmit,
      genderOptions,
      chooseMember,
      chooseMemberVisible,
      closeChooseMemberModal,
      handleMemberSelect,
      selectedMember,
      handleTagClose,
      roleList,
      departmentTreeData,
      imgAction: request.BASE_URL + "/public/system/uploadImage",
      fileList,
      handleUploadChange,
      politicalOptions,
      infoTabs,
      activeKey,
      filefaceImage,
      handleUploadFaceChange,
    };
  },
});

const genderOptions = [
  { label: "男", value: "1" },
  { label: "女", value: "2" },
  { label: "未知", value: "3" },
];
const politicalOptions = [
  { label: "团员", value: 1 },
  { label: "党员", value: 2 },
  { label: "预备党员", value: 3 },
  { label: "无党派人士", value: 4 },
  { label: "群众", value: 5 },
];
</script>

<style lang="less" scoped>
.mark-title {
  height: 20px;
  padding-left: 10px;
  position: relative;
  display: flex;
  align-items: center;
  font-size: 14px;
  font-weight: bold;
  //color: rgba(0, 0, 0, 0.8);
  &::before {
    position: absolute;
    content: "";
    left: 0;
    top: 2px;
    bottom: 2px;
    width: 4px;
    border-radius: 4px;
    background-color: @primary-color;
  }
}
:deep(.ant-upload.ant-upload-select-picture-card) {
  width: 90px;
  height: 90px;
}
:deep(.ant-upload-list-picture-card-container) {
  width: 90px;
  height: 90px;
}
</style>
